// var Ffmpeg = require('ffmpeg');
var childExec = require('child_process').exec;

try {

	var instructs = [
		// 'node -v',
		// 'set path=E:\\Dev\\ffmpeg-20181127-1035206-win64-static\\bin;%path%',
		// 'ffmpeg -y -f s16le -ac 1 -ar 8000 -i E:\\Test\\ffmpeg-test\\1.mp3  -acodec pcm_s16le -f s16le -ac 1 -ar 16000 E:\\Test\\ffmpeg-test\\1.mp3'

		'ls',
		'ls',
		'ls',
	];
	handleFFmpeg(instructs);

	// console.log('开始命令执行', instructs.join(' \n&&\n '));
	// exec(instructs.join('&&'), (error, stdout, stderr) => {
	// 	console.log('命令执行结果', { error, stdout, stderr });
	// });

	// var p1 = new Promise((resolve, reject) => {
	// 	exec('node -v', (error, stdout, stderr) => {
	// 		console.log('命令1', { error, stdout, stderr });
	// 		if (error) {
	// 			reject(error);
	// 		} else {
	// 			resolve(stdout);
	// 		}
	// 	});
	// });

	// p1.then(() => {
	// 	var p2 = new Promise((resolve, reject) => {
	// 		exec('set path=E:\\Dev\\ffmpeg-20181127-1035206-win64-static\\bin;%path%', (error, stdout, stderr) => {
	// 			console.log('命令2', { error, stdout, stderr });
	// 			if (error) {
	// 				reject(error);
	// 			} else {
	// 				resolve(stdout);
	// 			}
	// 		});
	// 	});

	// 	p1.then(() => {
	// 		new Promise((resolve, reject) => {
	// 			// exec('ffmpeg -y -f s16le -ac 1 -ar 8000 -i E:\\Test\\ffmpeg-test\\1.mp3  -acodec pcm_s16le -f s16le -ac 1 -ar 16000 E:\\Test\\ffmpeg-test\\1.mp3', (error, stdout, stderr) => {

	// 			exec('ffmpeg -i E:\\Test\\ffmpeg-test\\2.mp3 -id3v2_version 3 out2.mp3', (error, stdout, stderr) => {
	// 				console.log('命令3', { error, stdout, stderr });
	// 				if (error) {
	// 					reject(error);
	// 				} else {
	// 					resolve(stdout);
	// 				}
	// 			});
	// 		});

	// 	});

	// });






	// var process = new Ffmpeg("E:\Test\ffmpeg-test\1.mp3");

	// process.then(function (video) {

	// console.log('Audio video: ' + video);

	// // Callback mode
	// // video.fnExtractSoundToMP3('/path/to/your_audio_file.mp3', function (error, file) {
	// // if (!error)
	// // console.log('Audio file: ' + file);
	// // });
	// }, function (err) {
	// console.log('Error: ' + err);
	// });
} catch (e) {
	console.log(e.code);
	console.log(e.msg);
}



function handleFFmpeg(data) {
	if (!data) return;
	var promise = null;
	for (let i = 0, v = ''; i < data.length; i++) {
		v = data[i];
		console.log('HandleFFmpeg1 Running result：', v);

		if (promise) {
			promise = promise.then((r) => {
				console.log('HandleFFmpeg2 Running result：', r);
			});

		} else {
			promise = processFFmpeg(v).then((r) => {
				console.log('HandleFFmpeg3 Running result：', r);
			});

		}
	}
}

function processFFmpeg(instruct) {
	return new Promise((resolve, reject) => {
		childExec(instruct, { encoding: 'GBK' }, (error, stdout, stderr) => {
			const r = { error, stdout, stderr };
			console.log('ProcessFFmpeg Running instruct result：', r);
			if (error) {
				reject(r);
			} else {
				resolve(r);
			}
		});
	});
}